#!/bin/bash

source /home/shell/util.sh

function install () {
  requireJava
  current_version=`curl -sL https://mirrors.tuna.tsinghua.edu.cn/apache/zookeeper/current/|grep "bin.tar.gz"|perl -pe "s#.*<a href.*>(.*?)</a>.*#\1#g"`;
  download /opt/apache-zookeeper-bin.tar.gz https://mirrors.tuna.tsinghua.edu.cn/apache/zookeeper/current/${current_version}
  tar -xf /opt/apache-zookeeper-bin.tar.gz -C /opt/
  rm -rf /opt/apache-zookeeper-bin.tar.gz
  mv /opt/apache-zookeeper-*-bin /opt/zookeeper
}

function config () {

  read -p "zk端口[2181]：" zk_port
  zk_port=${zk_port:-"2181"}

  read -p "zk数据目录[/tmp/zookeeper]：" data_dir
  data_dir=${data_dir:-"/tmp/zookeeper"}

  read -p "自动清理时间（小时）[0]：" autopurge_purgeInterval
  autopurge_purgeInterval=${autopurge_purgeInterval:-"0"}

  if [[ "${autopurge_purgeInterval}" != "0" ]]; then
    read -p "保留数量[3]：" autopurge_snapRetainCount
    autopurge_snapRetainCount=${autopurge_snapRetainCount:-"3"}
  fi
  

  cp /opt/zookeeper/conf/zoo_sample.cfg /opt/zookeeper/conf/zoo.cfg

  sed -ri "/ZOOKEEPER_PREFIX=/a\JAVA_HOME=/opt/jdk" /opt/zookeeper/bin/zkEnv.sh
  sed -ri "s/clientPort=2181/clientPort="${zk_port}"/g" /opt/zookeeper/conf/zoo.cfg
  sed -ri "s#dataDir=/tmp/zookeeper#dataDir="${data_dir}"#g" /opt/zookeeper/conf/zoo.cfg
  sed -ri "s/#autopurge.purgeInterval=1/autopurge.purgeInterval="${autopurge_purgeInterval}"/g" /opt/zookeeper/conf/zoo.cfg
  if [[ "${autopurge_purgeInterval}" != "0" ]]; then
    sed -ri "s/#autopurge.snapRetainCount=3/autopurge.snapRetainCount="${autopurge_snapRetainCount}"/g" /opt/zookeeper/conf/zoo.cfg
  fi

  bash /opt/zookeeper/bin/zkServer-initialize.sh --force
  firewall-addport ${zk_port}
}

function run () {
bash /home/shell/serviced-install.sh<<EOF
2


zookeeper
/opt/zookeeper/bin/zkServer.sh start

/opt/zookeeper/bin/zkServer.sh restart
/opt/zookeeper/bin/zkServer.sh stop

EOF
  printInfo "==================zookeeper=================="
  printInfo "zookeeper ip="$host_addr
  printInfo `cat /opt/zookeeper/conf/zoo.cfg|grep clientPort`
  printInfo "==================zookeeper=================="
}

install && config && run